class EntitiesController < ApplicationController
  def index
    limit = params[:limit].nil? ? 20 : params[:limit].to_i
    total = Entity.count :conditions => params[:entity]
    
    results = Entity.find(:all, :conditions => params[:entity], :offset => params[:start], :limit => limit, :order => "#{params[:groupBy] || 'type'}, #{params[:sort]} #{params[:dir]}").collect do
      |e| e.attributes_before_type_cast.delete_if { |key, value| value.to_s.empty? }
    end if total > 0
    
    hash = { :results => results || [] }
    hash[:total] = total if total > limit
    
    render :json => hash.to_json
  end

  def show
    render :json => { :success => true, :data => format(Entity.find(params[:id]).attributes({ :except => [ 'id', 'created_at', 'updated_at' ] })) }.to_json
  end

  def new
    render :action => :edit
  end

  def create
    entity = Institution.new(params[:entity]) if params[:entity][:type] == 'Institution'
    entity = Individual .new(params[:entity]) if params[:entity][:type] == 'Individual'
    
    render :json => entity.save ? '' : errors_as_json(entity)
  end

  def update
    entity = Entity.find(params[:id])
    render :json => entity.update_attributes(params[:entity]) ? '' : errors_as_json(entity)
  end

  def destroy
    render :json => { :success => Entity.delete(params[:id]) }.to_json
  end

  private
  def errors_as_json(entity)
    { :success => false, :errors => format(entity.errors) }.to_json
  end

  def format(hash)
    hash.inject(Hash.new) do |accum, elem|
      accum["entity[#{elem[0]}]"] = elem[1] unless elem[1].to_s.empty?
      accum
	end
  end
end
